﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace OnlineLabManagement.Models
{
    public class LabAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            string currentArea = filterContext.HttpContext.Request.RequestContext.RouteData.DataTokens["area"] as string;
           string currentController = filterContext.HttpContext.Request.RequestContext.RouteData.GetRequiredString("controller");
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {

                if (currentArea == "AdminConsole" && currentController != "AdminAccount")
                {
                    filterContext.HttpContext.Response.Redirect("/AdminConsole/AdminAccount/Login");
                }
            }

            base.OnAuthorization(filterContext);
        }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //return base.AuthorizeCore(httpContext);
            var rd = httpContext.Request.RequestContext.RouteData;
            string currentAction = rd.GetRequiredString("action");
            string currentController = rd.GetRequiredString("controller");
            string currentArea = rd.DataTokens["area"] as string;


            if (httpContext.User != null
                && httpContext.User.Identity != null
                && httpContext.User.Identity.IsAuthenticated 
                && !httpContext.User.IsInRole("Admin")
                && currentArea == "AdminConsole")
            {             

              return false;
            }
            //if (httpContext.User.IsInRole("Admin") && currentArea==null)
            //{
            //    return false;
            //}
            return true;
        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            ViewDataDictionary viewData = new ViewDataDictionary();
            viewData.Add("Message", "You do not have sufficient privileges for this operation.");
            filterContext.Result = new ViewResult { MasterName = "", ViewName = "PrivilegesError", ViewData = viewData };
            //base.HandleUnauthorizedRequest(filterContext);
        }
    }
}